<?php

/*
 * Following code will list all the offers
 */

// array for JSON response
$response = array();


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// building the sql-statement
$statement = "SELECT off.*, Concat(usr.Firstname, ' ', usr.Lastname) as Name FROM Offer off INNER JOIN User usr ON usr.UserID = off.UserID ";
$statement .= "WHERE 1 ";

if(isset($_GET["OfferID"]))
{
	$statement .= "AND OfferID = " .$_GET["OfferID"] . " ";
}

if(isset($_GET["Type"]))
{
	$statement .= "AND Type = " .$_GET["Type"] . " ";
}

if(isset($_GET["FromSearchDeparture"]) && isset($_GET["ToSearchDeparture"]))
{
	$statement .= "AND DepartureFrom >= '" .$_GET["FromSearchDeparture"] . "' ";
	$statement .= "AND (DepartureTo >= '" .$_GET["ToSearchDeparture"] . "' ";
	$statement .= "OR DepartureTo IS NULL AND DepartureFrom <= '" .$_GET["ToSearchDeparture"] . "') ";
}

if(isset($_GET["SearchSource"]))
{
	$statement .= "AND (Source like '%" .$_GET["SearchSource"] . "%' ";	
	$statement .= "OR Over like '%" .$_GET["SearchSource"] . "%') ";
	$statement .= "AND Destination = 'FH Hagenberg' ";
}

if(isset($_GET["SearchDestination"]))
{
	$statement .= "AND (Destination like '%" .$_GET["SearchDestination"] . "%' ";
	$statement .= "OR Over like '%" .$_GET["SearchDestination"] . "%') ";
	$statement .= "AND Source = 'FH Hagenberg' ";
}

if(isset($_GET["onlyValid"]))
{
	$statement .= "AND (DepartureFrom > NOW() OR DepartureTo > NOW()) ";
}

$statement .= "Order by DepartureFrom";
$response["query"] = $statement;

// get all offers from offers table
$result = mysql_query($statement) or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // offers node
    $response["offers"] = array();
    
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $offer = array();
        $offer["OfferID"] = $row["OfferID"];
        $offer["Name"] = utf8_encode($row["Name"]);
        $offer["Type"] = $row["Type"];
        $offer["Source"] = utf8_encode($row["Source"]);
        $offer["Destination"] = utf8_encode($row["Destination"]);
        $offer["Over"] = utf8_encode($row["Over"]);
		$offer["DepartureFrom"] = $row["DepartureFrom"];
		$offer["DepartureTo"] = $row["DepartureTo"];
		$offer["Note"] = utf8_encode($row["Note"]);

        // push single offer into final response array
        array_push($response["offers"], $offer);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no offers found
    $response["success"] = 0;
    $response["message"] = "No offers found";

    // echo no users JSON
    echo json_encode($response);
}
?>
